package com.djl.rabbitmq.eight;

import com.djl.rabbitmq.utils.RabbitMqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: rabbitmq-hello
 * @description: 死信实战队列 消费者1
 * @author: Mr.dai
 * @create: 2021-09-13 10:08
 **/

public class ConSumer01 {
    //普通交换机名称
    public static  final  String NORMAL_EXCHANGE="normal_exchange";
    //死信交换机名称
    public static  final  String DEAD_EXCHANGE="dead_exchange";
//    普通队列名称
    public static final String NORMAL_QUEUE="normal_queue";
//    死信队列名称
    public static final String DEAD_QUEUE="dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        //声明交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        //声明死信队列和普通队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);

        Map<String, Object> arguments=new HashMap<>();
        //过期时间   一般由生产者设定
        //arguments.put("x-message-ttl","10000");
        //正常队列设置死信交换机
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //arguments.put("x-max-length",6);
        //设置死信routingkey
        arguments.put("x-dead-letter-routing-key","lisi");

        channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments);


        //绑定普通交换机与队列
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");
        //绑定死信交换机与队列
        DeliverCallback deliverCallback=( consumerTag,  message)->{
            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            if (msg=="info5"){
                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
            }
            System.out.println(msg);

        };

        channel.basicConsume(NORMAL_QUEUE,true, deliverCallback,consumerTag -> {

        });
    }



}
